package cn.nxcoder.blog.service.impl;

import cn.nxcoder.blog.core.AbstractService;
import cn.nxcoder.blog.dao.TagMapper;
import cn.nxcoder.blog.entity.Tag;
import cn.nxcoder.blog.entity.Type;
import cn.nxcoder.blog.service.TagService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 博客标签Service
 * @author shengwu ni
 * @date 2018/05/05 21:50
 */
@Service
public class TagServiceImpl extends AbstractService<Tag> implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public List<Tag> findTop10Tags() {
        List<Tag> tagList = tagMapper.selectAll();
        if (tagList != null && tagList.size() > 0) {
            if (tagList.size() <= 10) {
                return sortTags(tagList);
            } else {
                return sortTags(tagList).subList(0, 9);
            }
        }
        return null;
    }

    @Override
    public List<Tag> findAllTags() {
        List<Tag> tagList = tagMapper.selectAll();
        if (tagList != null && tagList.size() > 0) {
            return sortTags(tagList);
        }
        return null;
    }

    private List<Tag> sortTags(List<Tag> tagList) {

        for (Tag tag : tagList) {
            String blogid = tag.getBlogid();
            if (blogid != null && !"".equals(blogid)) {
                String[] split = blogid.split(",");
                tag.setBlogNum(split.length);
            } else {
                tag.setBlogNum(0);
            }
        }

        tagList.sort((o1, o2) -> o2.getBlogNum().compareTo(o1.getBlogNum()));
        return tagList;
    }
}
